package es.capgemini.extjsplugin.core;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.FieldDeclaration;
import org.eclipse.jdt.core.dom.Modifier;
import org.eclipse.jdt.core.dom.PackageDeclaration;
import org.eclipse.jdt.core.dom.SingleVariableDeclaration;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;

import es.capgemini.extjsplugin.wizard.GeneratorWizardModel;
/**
 * Clase para generar el Manager de la entidad
 * @author Lisandro Medrano
 *
 */
public class ManagerGenerator extends JavaFileGenerator {
	
	private String CLASS_URL;
	private String MANAGER_URL;
	private GeneratorWizardModel model;
	public ManagerGenerator(GeneratorWizardModel model) {
		this.package_url = model.getPackage_url();
	    this.package_name = model.getPackage_name();
	    this.package_base = model.getPackage_url();
	    this.class_name=model.getMyClass().getSimpleName();
	    this.camposIncluir=model.getCamposIncluir();
	    this.packageFragment=model.getPackageFragment();
	    this.model=model;
	    crearDirectorios();
	}
	
	protected void crearDirectorios() {
		//Creamos la estructura de src/
		super.crearDirectorios();
        
        File dir_package = new File(package_url + "/dto");
        dir_package.mkdirs();
        DTO_URL = dir_package.getAbsolutePath();
        MANAGER_URL = package_url;
    }
	/**
     * Crea el Manager
     */
    public void crearManager() {
        File file = null;

        file = new File(new File(MANAGER_URL) + "/" + class_name + "Manager.java");
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        PrintWriter out = null;
        try {
            out = new PrintWriter(new FileOutputStream(file));
        } catch (FileNotFoundException e) {

            e.printStackTrace();
        }
        out.println("package " + package_name + ";");
        out.println("/**");
        out.println(" * Creado el " + new Date());
        out.println(" * @author: Lisandro Medrano");
        out.println(" */");
        out.println("@Service");
        out.println("@Transactional");
        out.println("public class " + class_name + "Manager" + " {");
        out.println("\t@Autowired");
        out.println("\tprivate " + class_name + "Dao " + Utils.toLowerCamelCase(class_name) + "Dao;");

        // Si la clase tiene objetos tipo Diccionario agrego los DAo tambien
//        if (class_name.equals(myClass.getSimpleName())) {
//            for (Field f : myClass.getDeclaredFields()) {
//                Class cl[] = f.getType().getInterfaces();
//                for (Class c : cl) {
//                    if (c.getSimpleName().equals("Dictionary")) {
//                        daoGenerator.crearDao(f.getType().getSimpleName());
//                        daoGenerator.crearDaoImpl(f.getType().getSimpleName());
//                        out.println("\t@Autowired");
//                        out
//                                .println("\t" + f.getType().getSimpleName() + "Dao " + Utils.toLowerCamelCase(f.getType().getSimpleName().substring(2))
//                                        + "Dao;");
//
//                    }
//                }
//            }
//        }

        out.println("\t@BusinessOperation");
        out.println("\tpublic List<" + class_name + "> getList() {");
        out.println("\t\treturn " + Utils.toLowerCamelCase(class_name) + "Dao.getList();");
        out.println("\t}");

        out.println("\t@BusinessOperation");
        out.println("\tpublic " + class_name + " get(Long id) {");
        out.println("\t\treturn " + Utils.toLowerCamelCase(class_name) + "Dao.get(id);");
        out.println("\t}");

        out.println("\t@BusinessOperation");
        out.println("\tpublic " + class_name + " getInstance(Long id) {");
        out.println("\t\t//TODO:implementar metodo");
        out.println("\t}");

        out.println("\t@BusinessOperation");
        out.println("\t@Transactional(readOnly = true)");
        out.println("\tpublic void createOrUpdate(Dto" + class_name + " dto" + class_name + ") {");
        out.println("\t\t//TODO:implementar metodo");
        out.println("\t}");

        out.println("}");
        // Flush and close the stream
        out.flush();
        out.close();

    }
    /**
     * Crea la clase DTO 
     */
    public void crearDto() {
        File file = null;

        file = new File(new File(DTO_URL) + "/Dto" + class_name + ".java");
        try {
            file.createNewFile();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        PrintWriter out = null;
        try {
            out = new PrintWriter(new FileOutputStream(file));
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        out.println("package " + package_name + ".dto;");
        out.println("/**");
        out.println(" * Creado el " + new Date());
        out.println(" * @author: Lisandro Medrano");
        out.println(" */");
        out.println("public class Dto" + class_name + " extends WebDto {");
        out.println("\tprivate " + class_name + " " + Utils.toLowerCamelCase(class_name) + ";");
        out.println("\t\tpublic void validateFormulario(MessageContext messageContext) {");
        out.println("\t\t\tmessageContext.clearMessages();");
        out.println("\t\t\t//TODO:realizar validaciones");
        out.println("\t\t\taddValidation(" + Utils.toLowerCamelCase(class_name) + ", messageContext, \"" + Utils.toLowerCamelCase(class_name)
                + "\").addValidation(this, messageContext).validate();");
        out.println("\t\t}");
        out.println("\t\t\t//TODO:agregar setters/getters");
        out.println("}");
        out.flush();
        out.close();

    }
    public void managerCodeGeneration(){
//    	AST ast = AST.newAST(AST.JLS3);
//    	CompilationUnit cu=ast.newCompilationUnit();
//    	TypeDeclaration type=ast.newTypeDeclaration();
//    	type.setInterface(false);
//    	type.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));
//    	type.setName(ast.newSimpleName("DtoPrueba" + class_name));
//    	//type.setStructuralProperty(TypeDeclaration.SUPERCLASS_PROPERTY, "WebDto");
//    	MethodDeclaration methodDeclaration = ast.newMethodDeclaration();
//		methodDeclaration.setConstructor(false);
//		List modifiers = methodDeclaration.modifiers();
//		modifiers.add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));
//		methodDeclaration.setName(ast.newSimpleName("validateFormulario"));
//		methodDeclaration.setReturnType2(ast.newPrimitiveType(PrimitiveType.VOID));
//		SingleVariableDeclaration variableDeclaration = ast.newSingleVariableDeclaration();
//		variableDeclaration.setType(ast.newSimpleType(ast.newSimpleName("MessageContext")));
//		variableDeclaration.setName(ast.newSimpleName("messageContext"));
//		methodDeclaration.parameters().add(variableDeclaration);
//		cu.types().add(type);  	
//		cu.recordModifications();
    	
    }
}
